package com.wdzl.frame;

import com.wdzl.model.Card;
import com.wdzl.model.CardModel;
import com.wdzl.util.ImageUtil;
import com.wdzl.util.MouseAdapterFrame;
import com.wdzl.util.MyPlayer;
import com.wdzl.util.ShadowUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *
 */
public class GameFrame extends MouseAdapterFrame {

    private int width = 463;
    private int height = 830;
    private Card bg;
    private Card selectArea;

    private boolean isOver;// 是否失败
    private boolean isPass;// 是否通关

    //分类个数 本关卡显示的卡片类型数
    private int cardSortCount = 6;

    //要显示卡片数量
    private int centerCount=53; //中间塔型区域个数

    // 游戏失败图片
    Image overImg;
    Image passImg;

    public GameFrame(){
        initFrame();
        setVisible(true);
    }

    private void initFrame(){

        Image icon = ImageUtil.getByImgs("羊");
        setTitle("羊了个羊");
        setIconImage(icon);
        setSize(width,height);
        //默认居中显示
        setLocationRelativeTo(null);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        //设置为绝对布局
        setLayout(null);

        initPanel();

        //用于结束游戏时，点击确定后关闭
        addMouseListener(this);
    }

    /**
     * 初始化面板
     * 注意画的顺序先画在上后画在下
     */
    private void initPanel(){

        initRight1Area();
        initLeft1Area();
        initLeft2Area();
        initRight2Area();

        initTowerArea();

        initBackground();

//        repaint();
        new Thread(()->{MyPlayer.playMusic();}).start();
    }

    private void initBackground(){
        //初始化加载图片
        ImageIcon bgImage = ImageUtil.getImageIcon("imgs/背景草地.png");
        ImageIcon clearAreaImage = ImageUtil.getImageIcon("imgs/消除区域.png");
        overImg = ImageUtil.getByImgs("over");
        passImg = ImageUtil.getByImgs("ok");
        selectArea = new Card(clearAreaImage);
        System.out.println(getHeight()+"==="+clearAreaImage.getIconHeight());
        selectArea.setLocation(12,getHeight()-clearAreaImage.getIconHeight()*3/2);
        selectArea.setSize(clearAreaImage.getIconWidth(),clearAreaImage.getIconHeight());
        add(selectArea);

        bg = new Card(bgImage);
        bg.setLocation(0,0);
        bg.setSize(bgImage.getIconWidth(),bgImage.getIconHeight());
        add(bg);
    }

    /**
     * 绘制塔形区域
     */
    private void initTowerArea(){
        int index = 0;
        for (int i = 1; i <= CardModel.floorCountOfTower; i++) {
            // 下面绘制每一层n*n的卡片
            for (int x = 0; x < i; x++) {
                for (int y = 0; y < i; y++) {
                    Card card = CardModel.towerList.get(index);
                    card.setPosZ(i-1); // 塔顶为第0层
                    addInitCard(card,200-(i-1)*25+x*50,150-(i-1)*25+y*50);
                    if(index==0){
                        card.setGray(false);
                    }
                    index++;

                }
            }
        }
    }

    /**
     * 初始化左边1区域
     */
    private void initLeft1Area(){
        for (int i = CardModel.left1List.size()-1; i >=0; i--) {
            Card card = CardModel.left1List.get(i);
            if(i==CardModel.left1List.size()-1){
                card.setGray(false);
            }

            addInitCard(card,40+6*i,350);
//            add(card);
        }
    }
    /**
     * 初始化右边1区域
     */
    private void initRight1Area(){
        for (int i = 0; i < CardModel.right1List.size(); i++) {

            Card card = CardModel.right1List.get(i);
            if(i==0){
                card.setGray(false);
            }
//            card.setLocation(240+6*i,330);
            addInitCard(card,240+6*i,350);
        }
    }

    /**
     * 初始化右下区域
     */
    private void initRight2Area(){
        for (int i = 0; i < CardModel.right2List.size(); i++) {
            Card card = CardModel.right2List.get(i);
            addInitCard(card,300,450+6*i);
            if(i==0){
                card.setGray(false);
            }
        }
    }
    /**
     * 初始化右下区域
     */
    private void initLeft2Area(){
        for (int i = 0; i < CardModel.left2List.size(); i++) {
            Card card = CardModel.left2List.get(i);
            addInitCard(card,100,450+6*i);
            if(i==0){
                card.setGray(false);
            }
        }
    }

    private void addInitCard(Card card,int x,int y){
        card.setLocation(x,y);
        add(card);
        card.addMouseListener(this);
    }



    /**
     * 重置卡槽  传入刚刚选中添加卡槽的卡片
     */
    private void resetCardSlot(){
        //获取卡槽位置
        int x = selectArea.getX();
        int y = selectArea.getY();
        Collections.sort(CardModel.selectedList);

        //顺着设置位置，重新绘制
        for (int i = 0; i < CardModel.selectedList.size(); i++) {
            Card card = CardModel.selectedList.get(i);
            card.setLocation(x+20+i*55,y+28);
        }
    }





    /**
     * 处理塔形卡片被点击情况
     * @param card
     */
    private void towerListToSelectedList(Card card) {
        List<Card> list = CardModel.towerList;
        if(list.isEmpty()){
            return;
        }
        //从原所在区域列表中移除
        list.remove(card);

        //添加到卡槽区域列表中
        addToCardSlot(card);//添加到卡槽中

        //把下一个变为可以正常可点状态
        for (Card card1 : list) { //遍历所有的塔形区域的卡片
            //如果不是最底层 则判断下一层是否
            if(card.getPosZ()+1<CardModel.floorCountOfTower && card1.getPosZ()==card.getPosZ()+1){
                System.out.println(card1.getPosZ()+"==isHaveUpper=="+isHaveUpper(card1));
                if(!isHaveUpper(card1)){
                    System.out.println("===设置亮色====");
                    card1.setGray(false);
                }
            }
        }
    }

    /**
     * 判断card上层是否压牌的其他卡牌
     * @param card
     * @return
     */
    public boolean isHaveUpper(Card card){
        for (Card card1 : CardModel.towerList) {
            if(card1.getPosZ()==card.getPosZ()-1){ //只和上层判断
                if(card1.getBounds().intersects(card.getBounds()) ){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 非塔形区移卡
     * 从原有的区域列表中移到选中卡槽列表中
     */
    private void areaListToSelectedList(List<Card> list,int removeIndex){
//        List<Card> list = CardModel.left2List;
        if(list.isEmpty()){
            return;
        }
        //从原所在区域列表中移除
        Card card = list.remove(removeIndex);
        //把下一个变为可以正常可点状态
        if(list.isEmpty()==false){
            if(removeIndex != 0){ //表示从尾部移除的，则下一个需要变亮的卡片应该尾部减一
                removeIndex = removeIndex -1;
            }
            list.get(removeIndex).setGray(false);
        }

        //添加到卡槽区域列表中
        addToCardSlot(card);//添加到卡槽中
    }
    /**
     * 把选中的卡片添加到卡槽中
     * @param card
     */
    private void addToCardSlot(Card card) {
        move(card);
    }

    /**
     * 移动卡动画效果
     * @param card
     */
    public void move(Card card){
        new Thread(()->{
            int y0 = selectArea.getY()-card.getY();
            int x0 = selectArea.getX()-card.getX()+30+CardModel.selectedList.size()*50;

            int moveY = 60;
            int moveX = moveY * x0 / y0;

            while (card.getY()<selectArea.getY()){
                //防止最后一次加偏移量后，超出卡槽位置
                if(card.getY()+moveY > selectArea.getY()){
                    moveY = selectArea.getY()-card.getY();
                }
                card.setLocation(card.getX()+moveX,card.getY()+moveY);
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(isOver||isPass){ //如果线程没走完，游戏结束了，则停止
                    return;
                }
            }
            //完成动画后，添加到卡槽中
            addToCardSlotComplete(card);
        }).start();

        //完成动画后，添加到卡槽中
//        addToCardSlotComplete(card);
    }

    private void addToCardSlotComplete(Card card){
        if(isOver){
            return;
        }
        //被选中放入带消除卡槽中
        card.setSelected(true);
        CardModel.selectedList.add(card);
        //判断是否有相同的三个
        sameThreeRemove(card);

        //判断是否成功！
        isPass = CardModel.isOk();

        // 判断是否OVER
        isOver();

        //重绘卡槽
        resetCardSlot();




        repaint();
    }

    /**
     * 判断是否有相同的，然后消卡移除
     */
    private void sameThreeRemove(Card card){
        String name = card.getName();
        // 存放相同的卡，检查是否达到消除的数量
        List<Card> sameCards = new ArrayList<>();
        for (int i = 0; i < CardModel.selectedList.size(); i++) {
            Card c = CardModel.selectedList.get(i);
            //如果是相同图案的卡片
            if(c.getName().equals(card.getName())){
                sameCards.add(c);
            }
        }
        if(sameCards.size()>=3){
            for (Card sameCard : sameCards) {
                sameCard.setDeleted(true);
                sameCard.setVisible(false);
                CardModel.selectedList.remove(sameCard);
            }
        }

    }
    /**
     * 塔形区域点击事件处理
     */
    private void actionEvent_AREA_TYPE_CENTER_5(Card card){
//        areaListToSelectedList(CardModel.towerList,0);
        towerListToSelectedList(card);
    }
    private void actionEvent_AREA_TYPE_LEFT_1(){
        //表示从尾部开始移除
        int tail = CardModel.left1List.size()-1;
        areaListToSelectedList(CardModel.left1List,tail);
    }
    private void actionEvent_AREA_TYPE_LEFT_2(){
        //表示从开头开始移除
        areaListToSelectedList(CardModel.left2List,0);
    }
    private void actionEvent_AREA_TYPE_RIGHT_1(){
        //表示从开头开始移除
        areaListToSelectedList(CardModel.right1List,0);
    }
    private void actionEvent_AREA_TYPE_RIGHT_2(){
        //表示从开头开始移除
        areaListToSelectedList(CardModel.right2List,0);
    }





    @Override
    public void mousePressed(MouseEvent e) {
        // 用来处理点击确定按钮关闭游戏
        if(e.getSource() instanceof JFrame && (isOver||isPass)){
            //按钮区域
            if(e.getX()>=50 && e.getX()<getWidth()-50 && e.getY()>440 && e.getY()<500){
                MyPlayer.stop(); //停止背景音乐
                setVisible(false);
                dispose();
            }
            return ;
        }

        if(isOver || e.getSource() instanceof Card == false){
            return;
        }
        //被点击卡片
        Card card = (Card) e.getSource();
        if(card.isDeleted() || card.isGray() || card.isSelected()){
            return;
        }
//        System.out.println("======mouseClicked===="+card.getAreaType());

        switch (card.getAreaType()){
            case CardModel.AREA_TYPE_CENTER_5:
                actionEvent_AREA_TYPE_CENTER_5(card);
                break;
            case CardModel.AREA_TYPE_LEFT_2:
                actionEvent_AREA_TYPE_LEFT_2();
                break;
            case CardModel.AREA_TYPE_RIGHT_1:
                actionEvent_AREA_TYPE_RIGHT_1();
                break;
            case CardModel.AREA_TYPE_RIGHT_2:
                actionEvent_AREA_TYPE_RIGHT_2();
                break;
            case CardModel.AREA_TYPE_LEFT_1:
                actionEvent_AREA_TYPE_LEFT_1();
                break;
        }


        //重新绘制
        repaint();
    }

    /**
     * 判断游戏是否结束
     */
    public void isOver(){
        if(CardModel.selectedList.size()>=CardModel.CARD_SLOT_COUNT){
            isOver = true;
        }
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if(isOver){
            int rule = AlphaComposite.SRC_OVER;
            float alpha = 0.7F;
            ((Graphics2D) g).setComposite(AlphaComposite.getInstance(rule, alpha));
            g.fillRect(0,0,getWidth(),getHeight());

            // 绘制结束提示框
            alpha = 1F;
            ((Graphics2D) g).setComposite(AlphaComposite.getInstance(rule, alpha));

            g.drawImage(overImg,80,360,null);
        }
        if(isPass){
            //通关
            //绘制罩影
            ShadowUtil.drawShadow(g,0,0,getWidth(),getHeight());

            // 绘制结束提示框  这里需要恢复透明度
            float alpha = 1F;
            ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

            g.drawImage(passImg,80,360,null);
        }

    }
}
